//
//  FNiOSApp.swift
//  FNiOS
//
//  Created by mac on 2023/3/13.
//

import SwiftUI

import Flutter
// The following library connects plugins with iOS platform code to this app.
import FlutterPluginRegistrant

class FlutterDependencies: ObservableObject {
    let flutterEngine = FlutterEngine(name: "my flutter engine")
    init(){
        // Runs the default Dart entrypoint with a default Flutter route.
        flutterEngine.run()
        
        // 添加 MethodChannel 互传数据
        // 创建 channel
        let methodChannel = FlutterMethodChannel(
            name: "flutter_bridge",
            binaryMessenger: flutterEngine.binaryMessenger,
            codec: FlutterStandardMethodCodec.sharedInstance()
        )
        // 绑定事件
        methodChannel.setMethodCallHandler({
            (call:FlutterMethodCall, result:FlutterResult) -> Void in
            
            switch call.method
            {
            case "Text":
                result("IOS-Text 返回数据， 继续累加 +1")
                break;
            case "Native":
                result("IOS-Native 返回数据， 继续累加 +2")
                break;
            case "Back":
                // Get the RootViewController.
                guard
                    let windowScene = UIApplication.shared.connectedScenes
                        .first(where: { $0.activationState == .foregroundActive && $0 is UIWindowScene }) as? UIWindowScene,
                    let window = windowScene.windows.first(where: \.isKeyWindow),
                    let rootViewController = window.rootViewController
                else { return }
                rootViewController.dismiss(animated: true)
                
                
                break;
            default:
                break;
            }
        })
        
        // Connects plugins with iOS platform code to this app.
        GeneratedPluginRegistrant.register(with: self.flutterEngine);
    }
}

@main
struct FNiOSApp: App {
    // flutterDependencies will be injected using EnvironmentObject
    // 全局的 flutter 依赖
    @StateObject var flutterDependencies = FlutterDependencies()
    
    var body: some Scene {
        
        WindowGroup {
            ContentView().environmentObject(flutterDependencies)
        }
    }
    init(){
        // 打印宽高
        print("==== 屏幕宽高 ====")
        print("\(UIScreen.main.bounds.width) x \(UIScreen.main.bounds.height)")
        print("================")
    }
}
